import { IItem, IFlattenedItem } from '../store/itemsStore'

let ActiveItem: IItem | null = null

// 函数findActiveItem用于查找items数组中id为activeId的元素，并将其赋值给ActiveItem
function findActiveItem(items: IItem[], activeId: string) {
  // 遍历items数组
  items.forEach((item) => {
    // 如果当前元素的id等于activeId，则将其赋值给ActiveItem
    if (item.id === activeId) {
      ActiveItem = { ...item }
      return
    }
    // 如果当前元素有子元素，则递归调用findActiveItem函数
    if (item.children) {
      findActiveItem(item.children, activeId)
    }
  })
}

function insertActiveItem(
  items: IItem[],
  activeId: string,
  activeIndex: number,
  overId: string,
  overIndex: number,
  insertFirst: boolean
): IItem[] {
  let hasOverId = false
  const newItems = items.map((item): IItem & { isActive?: boolean } => {
    if (item.id === activeId) {
      return { ...item, isActive: true } // 标记 active 以便后面 filter
    }
    if (item.id === overId) {
      hasOverId = true
    }
    return {
      ...item,
      children: item.children
        ? insertActiveItem(
            item.children,
            activeId,
            activeIndex,
            overId,
            overIndex,
            insertFirst
          )
        : item.children,
    }
  })

  if (hasOverId && ActiveItem) {
    const overItemIndex = newItems.findIndex((item) => item.id === overId)
    if (overItemIndex === 0 && insertFirst) {
      newItems.unshift(ActiveItem)
    } else if (overItemIndex > -1) {
      const startIndex =
        activeIndex < overIndex ? overItemIndex + 1 : overItemIndex
      newItems.splice(startIndex, 0, ActiveItem)
    }
  }

  return newItems.filter((item) => !item.isActive)
}

// 导出一个默认函数，用于生成新的项目
export default function genNewItems(
  // 项目数组
  items: IItem[],
  // 展平的项目数组
  flattenedItems: IFlattenedItem[],
  // 活动项目的id
  activeId: string,
  // 覆盖项目的id
  overId: string
): IItem[] {
  // 在展平的项目数组中找到活动项目的索引
  const activeIndex = flattenedItems.findIndex((i) => i.id === activeId)
  // 在展平的项目数组中找到覆盖项目的索引
  const overIndex = flattenedItems.findIndex((i) => i.id === overId)

  // 定义一个变量，用于判断是否在覆盖项目的第一个子节点之前插入活动项目
  let insertFirst = false
  // 如果活动项目的索引小于覆盖项目的索引
  if (activeIndex < overIndex) {
    // 获取覆盖项目
    const over = flattenedItems[overIndex]
    // 获取覆盖项目的下一个项目
    const nextOver = flattenedItems[overIndex + 1]
    // 如果下一个项目存在，并且下一个项目的祖先id中包含覆盖项目的id
    if (nextOver && nextOver.ancestorIds?.includes(over.id)) {
      // 将覆盖项目的id设置为下一个项目的id
      overId = nextOver.id
      // 将insertFirst设置为true
      insertFirst = true
    }
  }

  // 1. Find the active item
  ActiveItem = null
  findActiveItem(items, activeId)
  if (ActiveItem === null) {
    return items
  }

  // 2. Insert the active item into the new position, and return the new items
  const newItems = insertActiveItem(
    items,
    activeId,
    activeIndex,
    overId,
    overIndex,
    insertFirst
  )

  // 3. Return the new items
  return newItems
}
